package com.jzy.dl.common.config;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.jzy.dl.common.utils.Global;

/**
 * 
 * 类描述： 过滤打印所有请求
 * 创建者： jiaozy
 * 项目名称： darkLine
 * 创建时间： 2019年6月20日 上午9:48:25
 * Email：jzy19890914@gmail.com
 */
@Component//将此Filter交给Spring容器管理
@WebFilter(urlPatterns = "/*", filterName = "myUrlFilter")
@Order(1)//指定过滤器的执行顺序,值越大越靠后执行
public class UrlFilter implements Filter{
	
	private static Logger logger=LoggerFactory.getLogger(UrlFilter.class);
	
	private final static String ENCODING="UTF-8";
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse res=(HttpServletResponse)response;
		req.setCharacterEncoding(ENCODING);
		res.setCharacterEncoding(ENCODING);
		
		String uri=req.getRequestURI();
		
		LocalDateTime startTime= LocalDateTime.now(Global.CHINA_ZONEID);
		logger.debug("");
		logger.debug("-------------------------------request start-------------------------------");
		logger.debug( "URI：{}，进入时间：{}",req.getRequestURI(),Global.DATE_FOMAT.format(startTime));
		
		chain.doFilter(request, response);
		
		LocalDateTime endTime= LocalDateTime.now(Global.CHINA_ZONEID);
		
		BigDecimal oneM=BigDecimal.valueOf(1024 * 1024);
		//JVM最大可用内存总数(M)
		BigDecimal max = BigDecimal.valueOf((Runtime.getRuntime().maxMemory())).divide(oneM,4,BigDecimal.ROUND_HALF_UP); 
		//当前JVM占用的内存总数(M)
		BigDecimal total = BigDecimal.valueOf(Runtime.getRuntime().totalMemory()).divide(oneM,4,BigDecimal.ROUND_HALF_UP);  
		//JVM空闲内存(M)
		BigDecimal free = BigDecimal.valueOf(Runtime.getRuntime().freeMemory()).divide(oneM,4,BigDecimal.ROUND_HALF_UP);
		//可用内存内存(M)
		BigDecimal mayuse=max.subtract(total).add(free);
		//已经使用内存(M)
		BigDecimal used=total.subtract(free);
		
		logger.debug("URI：{}，退出时间： {}，耗时：{}秒，最大可申请内存：{}M，已分配内存：{}M，剩余可申请内存：{}M，已用内存：{}M",
				req.getRequestURI(),
				Global.DATE_FOMAT.format(endTime),
				Duration.between(startTime, endTime).getSeconds(),
				max,total,used,mayuse);
		logger.debug("-------------------------------request end-------------------------------");
	}

}
